package com.zwy.Shopping.servlet_;

import com.zwy.Shopping.dao.ProductDao;
import com.zwy.Shopping.dao.impl.ProductDaoImpl;
import com.zwy.Shopping.model.Category;
import com.zwy.Shopping.model.Product;

import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sound.sampled.Port;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

@WebServlet("/add_product")
@MultipartConfig
public class AddProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("productName");
        String marketPriceStr = request.getParameter("productMarketPrice");
        String priceStr = request.getParameter("productPrice");
        String stockStr = request.getParameter("productStock");
        String categoryIdStr = request.getParameter("categoryId");
        Part part = request.getPart("productImage");
        String imageName = part.getSubmittedFileName();
        ProductDao productDao = new ProductDaoImpl();
        Product product = new Product();
        product.setName(name);
        product.setImage(imageName);
        product.setPrice(new BigDecimal(priceStr));
        product.setMarketPrice(new BigDecimal(marketPriceStr));
        product.setStock(Integer.parseInt(stockStr));
        Category category = new Category();
        category.setId(Integer.parseInt(categoryIdStr));
        product.setCategory(category);
        boolean success = productDao.add(product);
        if(success) {
            String path2 = "D:\\学习\\服装购买系统\\ShoppingClothes\\out\\artifacts\\ShoppingClothes_Web_exploded\\img\\";
            String webPath = path2 + imageName;
            File fileOnWeb = new File(webPath);
            if (fileOnWeb.exists()) {
                fileOnWeb.delete();
            }
            part.write(webPath);
            String localPath = "D:\\学习\\服装购买系统\\ShoppingClothes\\web\\img\\" + imageName;
            File fileOnLocal = new File(localPath);
            if (fileOnLocal.exists()) {
                fileOnLocal.delete();
            }
            Files.copy(fileOnWeb.toPath(), fileOnLocal.toPath(), StandardCopyOption.REPLACE_EXISTING); // 使用Java NIO复制文件
            request.setAttribute("message", "添加成功");
            request.setAttribute("page", "admin_index.jsp");
            request.getRequestDispatcher("alert.jsp").forward(request, response);
        }else {
            request.setAttribute("message", "添加失败");
            request.setAttribute("page", "admin_index.jsp");
            request.getRequestDispatcher("alert.jsp").forward(request, response);
        }

    }
}
